package com.example.lzwphoto.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.lzwphoto.common.R;
import com.example.lzwphoto.enity.Photo;
import com.example.lzwphoto.service.impl.PhotoServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Desc: TODO
 * @Author: LvKun
 * @Date: 2024-02-05
 * @Version: 1.0
 */

@RestController
@RequestMapping("/photo")
public class PhotoController {

    @Autowired
    private PhotoServiceImpl photoServicel;

    @GetMapping("{categoryId}")
    public R<List> list (@PathVariable Long categoryId) {

        List<Photo> collect = photoServicel.list().stream().filter(item -> item.getCategoryId().equals(categoryId)).collect(Collectors.toList());

        return R.success(collect);
    }

    @GetMapping("/page")
    public R<Page> page (int page ) {
        Page<Photo> pageinfo = new Page(page, 10);

        LambdaQueryWrapper<Photo> lqw = new LambdaQueryWrapper<>();

        photoServicel.page(pageinfo, lqw);

        return  R.success(pageinfo);
    }

    @DeleteMapping("{id}")
    public R<String> del (@PathVariable Long id) {

        photoServicel.delPhotoByServiceMachinePath(id);

        photoServicel.removeById(id);

        return  R.success("删除成功");
    }

    @PostMapping
    public R<String> save (
            @RequestParam("categoryId") Long categoryId,
            @RequestParam("file") MultipartFile file
    ) {

        if (file.isEmpty()) {
            return  R.error("文件不能为空");
        }

        String path = this.Upload(file);

        Photo photo = new Photo();

        photo.setCategoryId(categoryId);

        String fileName = file.getOriginalFilename();

        photo.setName(fileName);

        photo.setPath(path);

        photoServicel.save(photo);

        return R.success("保存成功, 保存路径：" + file.getName());
    }

    public String Upload (@RequestParam("file") MultipartFile file) {

        try {
            String fileName = file.getOriginalFilename();

            // 设置文件存储路径
            String workingDir = System.getProperty("user.dir");
            String filePath = workingDir + "/photo/" + fileName;

            File dest = new File(filePath);

            // 将文件保存到指定路径
            file.transferTo(dest);

            return filePath;

        } catch (IOException e) {
            R.error(e.toString());
            return  "";
        }
    }

}
